package club.zbiao.modules.system.service.spec;

import club.zbiao.modules.system.domain.Dept;
import club.zbiao.modules.system.domain.Job;
import club.zbiao.modules.system.service.dto.JobDTO;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by zhb on 2019/5/23.
 */
@Component
public class JobSpec implements BaseSpec<JobDTO,Job> {

    private JobDTO job;
    private Long deptId;
    private Set<Long> deptIds;

    public void init(JobDTO job){
        this.job = job;
        this.deptIds = job.getDeptIds();
        this.deptId = job.getDeptId();
    }

    @Override
    public Predicate toPredicate(Root<Job> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {

        List<Predicate> list = new ArrayList<Predicate>();

        // 数据权限
        Join<Dept, Job> join = root.join("dept",JoinType.LEFT);
        if (!CollectionUtils.isEmpty(deptIds)) {
            list.add(join.get("id").in(deptIds));
        }

        if(!ObjectUtils.isEmpty(job.getEnabled())){
            /**
             * 精确
             */
            list.add(cb.equal(root.get("enabled").as(Boolean.class),job.getEnabled()));
        }

        if(!ObjectUtils.isEmpty(job.getName())){
            /**
             * 模糊
             */
            list.add(cb.like(root.get("name").as(String.class),"%"+job.getName()+"%"));
        }

        if (deptId != null) {
            /**
             * 精确
             */
            list.add(cb.equal(join.get("id").as(Long.class),deptId));
        }
        Predicate[] p = new Predicate[list.size()];
        return cb.and(list.toArray(p));
    }
}
